<?php

namespace app\controllers;

use yii;
use yii\web\Controller;
use app\models\Modules;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use app\lib\BaseFunction;
use app\service\LoginService;
use app\lib\Redis;
use app\lib\Base;

class CommonController extends Controller
{
    use Redis;
    use Base;

    public $admin_role;
    public $enableCsrfValidation = false;
    public $user;

    public function beforeAction($action)
    {

        if (!$jwt = $this->getToken()) {
            $this->redirect('/login/index');
            return false;
        }
        $token = (new Parser())->parse($jwt);
        $expire = $token->getClaim('expire_time');
        //token验证 和过期验证
        if (!$token->verify((new Sha256()), yii::$app->params['jwt_token']) || time() > $expire) {
            echo json_encode(['code' => 401, 'msg' => '认证过期']);
            return false;
        }

        $this->user = $this->currentUser();

        $this->admin_role = $this->user['role'];
        yii::$app->view->params['admin_role'] = $this->admin_role;
        //最后20分钟重新生成jwT
        if ((time() + 1200) > $expire) {
            $base = new BaseFunction();
            $token = $base->generate_jwt($token->getClaim('id'), $token->getClaim('zh_name'));
            $cookie = new \yii\web\Cookie(['name' => 'jwt', 'value' => $token, 'expire' => time() + 3600 * 24]);
            yii::$app->response->cookies->add($cookie);
        }


        //检测报销
        if (isset($this->user['job_number']) && $this->user['job_number'] == 999) {
            if (BaseFunction::check_baoxiao()) {
                yii::$app->view->params['baoxiao'] = 1;
            }
        }
        $loginService = new LoginService();

        //当前用户所有权限
        $rulesInfo = $loginService->getRoleRules($this->user['role']);
        $rules = explode(',', $rulesInfo['role_rules']);

        $currentUrl = $_SERVER['REQUEST_URI'];

        //header nav
        $modules = new Modules();
        $list = $modules->all();

        $tmp = false;
        foreach ($list as $v) {
            if ($v['url'] != '') {
                if (!is_bool(strpos($currentUrl, $v['url']))) {
                    $tmp = true;
                    if (!in_array($v['id'], $rules)) {
                        return json_encode(['code' => 0, 'msg' => '非法登录']);
                    } else {
                        if ($v['module'] == 1) {
                            $module = $v['id'];
                        } else {
                            $module = explode('-', $v['list'])[1];

                        }
                    }
                }
            }
        }
        if (!$tmp) {
            //url未匹配到直接返回
//            return parent::beforeAction($action);
            $name = yii::$app->controller->id;
            foreach ($list as $v) {
                if ($v['module'] == 1) {
                    if (!is_bool(strpos($v['url'], $name))) {
                        $module = $v['id'];
                    }
                }
            }
        }
        if ($tmp) {
            foreach ($list as $k => $v) {
                if (!in_array($v['id'], $rules)) {
                    unset($list[$k]);
                }
            }
            $havePremission = false;
            foreach ($list as $key => $value) {
                if ($value['module'] !=2) {
                    if (!is_bool(strpos($currentUrl, $value['url']))) {
                        $havePremission = true;
                    }
                }
            }
            if (!$havePremission) {
                return $this->redirect('/login/index');
            }
        }
            foreach ($list as $v) {
                if ($v['module'] == 1) {
                    $nav[] = $v;
                } else {
                    if ($module == explode('-', $v['list'])[1]) {
                        $tmp1[] = $v;
                    }
                }

            }
            if(isset($nav)) {
                $nav = $this->mysort($nav, 'order_id');
                yii::$app->view->params['nav'] = $nav;
            }

            if (isset($tmp1)) {
                $left_nav = $this->mysort($tmp1, 'order_id');
                yii::$app->view->params['left_nav'] = $left_nav;
            }
        

        yii::$app->view->params['token'] = (string)$token;
        yii::$app->view->params['name'] = $this->user['name'];

        return parent::beforeAction($action);
    }

    /**获取excel对象
     * @param $file_path
     * @param $ext
     * @return \PHPExcel
     * @throws \PHPExcel_Reader_Exception
     */
    public
    function get_excel($file_path, $ext)
    {
        if ($ext == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($file_path, 'utf-8');
        } elseif ($ext == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($file_path, 'utf-8');
        }

        return $objPHPExcel;
    }


//数据排序
    public
    function get_tree($categories)
    {
        $tree = array();

        foreach ($categories as $category) {
            $tree[$category['id']] = $category;
            $tree[$category['id']]['children'] = array();
        }

        foreach ($tree as $key => $item) {
            if ($item['pid'] != 0) {
                $tree[$item['pid']]['children'][] = &$tree[$key];
                if ($tree[$key]['children'] == null) {
                    unset($tree[$key]['children']);
                }
            }
        }

        foreach ($tree as $key => $category) {
            if ($category['pid'] != 0) {
                unset($tree[$key]);
            }
        }
        //echo json_encode($tree);exit;
        return $tree;
    }

    public
    function get_folder()
    {
        $path = ROOT_PATH . DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR . date('Y-m-d');
        if (!file_exists($path)) {
            mkdir($path, 0766, 1);
        }
        return $path;
    }

    public
    function get_base_url()
    {
        $query_str = $_SERVER['QUERY_STRING'];
        if ($query_str) {
            $arr = explode('&', $query_str);
            $query_arr = [];
            foreach ($arr as $k => $v) {
                $tmp = explode('=', $v);
                if (!($tmp[0] == 'p')) {
                    $query_arr[] = $v;
                }
            }
            $base_url = "?" . implode('&', $query_arr);
        } else {
            $base_url = "";
        }
        return $base_url;
    }


    public
    function get_excel_writer($objPHPExcel)
    {
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        return $objWriter;
    }

    public
    function get_excel_draw()
    {
        $draw_excel = new \PHPExcel_Worksheet_Drawing();
        return $draw_excel;
    }

    public
    function check_img($input_type)
    {
        $type = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'];
        if (in_array($input_type, $type)) {
            return 1;
        } else {
            return 0;
        }
    }


    /**服务费
     * @param $money
     * @return array
     */
    public
    function service_pay($money)
    {
        if ($money <= 1000) {
            return [100];
        } elseif ($money > 1000 && $money < 2000) {
            return [$money * 10 / 100, '10%'];
        } elseif ($money >= 2000 && $money < 3000) {
            return [$money * 9 / 100, '9%'];
        } elseif ($money >= 3000 && $money < 5000) {
            return [$money * 8.5 / 100, '8.5%'];
        } elseif ($money >= 5000 && $money < 7000) {
            return [$money * 8 / 100, '8%'];
        } elseif ($money >= 7000 && $money < 10000) {
            return [$money * 7.5 / 100, '7.5%'];
        } elseif ($money >= 10000 && $money < 15000) {
            return [$money * 7 / 100, '7%'];
        } elseif ($money >= 15000 && $money < 20000) {
            return [$money * 6.5 / 100, '6.5%'];
        } elseif ($money >= 20000 && $money < 25000) {
            return [$money * 6 / 100, '6%'];
        } elseif ($money >= 25000 && $money < 30000) {
            return [$money * 5.5 / 100, '5.5%'];
        } elseif ($money >= 30000) {
            return [$money * 5 / 100, '5%'];
        }
    }

    public function mysort($arr, $param)
    {
        usort($arr, function ($a, $b) use ($param) {
            if ($a[$param] > $b[$param]) {
                return 1;
            } else {
                return -1;
            }
        });
        return $arr;
    }

    public function __call($method, $args)
    {
        echo 404;
    }

    public function actionError()
    {
        $this->layout = false;
        return $this->render('/public/404');
    }

    public function actionUploadImg()
    {
        $file = $_FILES['img'];
        if ($this->check_img($file['type'])) {
            $this->get_folder();
            $suffix = explode('.', $file['name']);
            $fileName = substr(md5($file['name'] . time()), 16) . '.' . $suffix[1];
            $path = '/upload/' . date('Y-m-d') . '/' . $fileName;
            $re = move_uploaded_file($file['tmp_name'], ROOT_PATH . $path);
            $path = 'https://' . $_SERVER['SERVER_NAME'] . $path;
            if ($re) {
                return json_encode(['code' => 1, 'msg' => $path]);
            } else {
                return json_encode(['code' => 0, 'msg' => '上传失败,请重试']);
            }
        }
    }

    public function validateRules($rules)
    {
        $data = yii::$app->request->post();
        foreach ($rules as $v) {
            if (!isset($data[$v])) {
                return 0;
            }
        }
        return 1;
    }
}
